<template>
  <div class="seller-product-manage">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="content-header">
        <h1>商品管理</h1>
        <p>管理您的商品信息，包括添加、编辑、删除和上下架操作</p>
      </div>

      <!-- 操作工具栏 -->
      <div class="toolbar">
        <div class="search-section">
          <div class="search-group">
            <input
              v-model="searchKeyword"
              type="text"
              placeholder="搜索商品名称..."
              class="search-input"
              @keyup.enter="handleSearch"
            />
            <button class="search-btn" @click="handleSearch">
              <i class="icon">🔍</i>
              搜索
            </button>
          </div>

          <div class="filter-group">
            <select v-model="statusFilter" @change="handleSearch" class="status-filter">
              <option value="">全部状态</option>
              <option value="1">上架中</option>
              <option value="0">已下架</option>
            </select>
          </div>
        </div>

        <div class="action-section">
          <button class="add-btn" @click="showAddModal">
            <i class="icon">➕</i>
            添加商品
          </button>
          <button class="refresh-btn" @click="refreshData" :disabled="loading">
            <i class="icon">🔄</i>
            {{ loading ? '加载中...' : '刷新' }}
          </button>
          <button class="export-btn" @click="exportToExcel">
            <i class="icon">📊</i>
            导出 Excel
          </button>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="product-list" v-if="!loading">
        <div class="list-header">
          <div class="header-item product-info">商品信息</div>
          <div class="header-item price">价格</div>
          <div class="header-item stock">库存</div>
          <div class="header-item status">状态</div>
          <div class="header-item actions">操作</div>
          <div class="header-item create-time">创建时间</div>
          <div class="header-item update-time">更新时间</div>
        </div>

        <div class="list-body">
          <div
            v-for="product in productList"
            :key="product.productId"
            class="product-item"
          >
            <div class="product-info">
              <div class="product-image">
                <img
                  :src="getImageSrc(product.productImage)"
                  :alt="product.productName"
                  class="product-img"
                />
              </div>
              <div class="product-details">
                <h3 class="product-name">{{ product.productName }}</h3>
                <p class="product-description">{{ product.productDescription || '暂无描述' }}</p>
                <span class="product-id">ID: {{ product.productId }}</span>
                <span class="product-sales">销量: {{ product.productSale }}</span>
                <span class="product-views">浏览: {{ product.productViewCount }}</span>
              </div>
            </div>

            <div class="price">
              <span class="current-price">¥{{ formatPrice(product.productPrice) }}</span>
            </div>

            <div class="stock">
              <span :class="product.productStock < 10 ? 'low-stock' : 'normal-stock'">
                {{ product.productStock }}
              </span>
            </div>

            <div class="status">
              <span class="status-badge" :class="product.status === 1 ? 'active' : 'inactive'">
                {{ product.status === 1 ? '上架中' : '已下架' }}
              </span>
            </div>

            <div class="actions">
              <button class="action-btn view-btn" @click="viewProduct(product)">
                <i class="icon">👁️</i>
                查看
              </button>
              <button class="action-btn sku-btn" @click="manageProductSku(product)">
                <i class="icon">📋</i>
                规格管理
              </button>
              <button class="action-btn add-sku-btn" @click="showAddSkuForm(product)">
                <i class="icon">➕</i>
                添加规格
              </button>
              <button 
                class="action-btn status-btn" 
                :class="product.status === 1 ? 'offline' : 'online'"
                @click="updateProductStatus(product.productId, product.status === 1 ? 0 : 1)"
              >
                <i class="icon">{{ product.status === 1 ? '📤' : '📥' }}</i>
                {{ product.status === 1 ? '下架' : '上架' }}
              </button>

            </div>
            <div class="create-time">
              {{ product.createTime }}
            </div>
            <div class="update-time">
              {{ product.updateTime }}
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="productList.length === 0" class="empty-state">
          <div class="empty-icon">📦</div>
          <h3>暂无商品</h3>
          <p>您还没有添加任何商品，点击上方"添加商品"按钮开始添加</p>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>

      <!-- 分页组件 -->
      <div class="pagination" v-if="totalItems > 0">
        <button
          class="page-btn"
          @click="changePage(1)"
          :disabled="currentPage <= 1 || totalPages <= 1"
        >
          首页
        </button>

        <button
          class="page-btn"
          @click="changePage(currentPage - 1)"
          :disabled="currentPage <= 1"
        >
          上一页
        </button>

        <div class="page-numbers">
          <button
            v-for="page in visiblePages"
            :key="page"
            class="page-number"
            :class="{ active: page === currentPage }"
            @click="changePage(page)"
            :disabled="totalPages <= 1"
          >
            {{ page }}
          </button>
        </div>

        <button
          class="page-btn"
          @click="changePage(currentPage + 1)"
          :disabled="currentPage >= totalPages"
        >
          下一页
        </button>

        <button
          class="page-btn"
          @click="changePage(totalPages)"
          :disabled="currentPage >= totalPages || totalPages <= 1"
        >
          末页
        </button>

        <div class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页，总计 {{ totalItems }} 条
        </div>

        <div class="page-size-selector">
          <label>每页显示：</label>
          <select v-model="pageSize" @change="changePageSize" class="page-size-dropdown">
            <option :value="5">5条</option>
            <option :value="10">10条</option>
            <option :value="20">20条</option>
            <option :value="50">50条</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 添加/编辑商品模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>{{ isEditing ? '编辑商品' : '添加商品' }}</h2>
          <button class="close-btn" @click="closeModal">✕</button>
        </div>

        <div class="modal-body">
          <form @submit.prevent="submitProduct">
            <div class="form-group">
              <label>商品名称 *</label>
              <input
                v-model="productForm.productName"
                type="text"
                required
                placeholder="请输入商品名称"
                class="form-input"
              />
            </div>

            <div class="form-group">
              <label>商品描述</label>
              <textarea
                v-model="productForm.productDescription"
                placeholder="请输入商品描述"
                rows="4"
                class="form-textarea"
              ></textarea>
            </div>

            <div class="form-group">
              <label>商品分类 *</label>
              <select
                v-model="productForm.categoryId"
                required
                class="form-select"
              >
                <option :value="null">请选择分类</option>
                <option
                  v-for="category in categoryList"
                  :key="category.id"
                  :value="category.id"
                >
                  {{ category.name }}
                </option>
              </select>
            </div>

            <div class="form-group">
              <label>主图片 *</label>
              <div class="main-image-upload">
                <input
                  type="file"
                  ref="mainImageInput"
                  @change="handleMainImageUpload"
                  accept="image/*"
                  style="display: none"
                />
                <div class="upload-area main-upload" @click="$refs.mainImageInput.click()">
                  <img
                    v-if="productForm.productImage"
                    :src="productForm.productImage"
                    alt="主图片预览"
                    class="preview-image"
                  />
                  <div v-else class="upload-placeholder">
                    <i class="icon">📷</i>
                    <p>点击上传主图片</p>
                    <span class="upload-tip">建议尺寸：800x800px</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="form-group">
              <label>商品图片集</label>
              <div class="images-upload">
                <div class="images-grid">
                  <div
                    v-for="(image, index) in uploadedImages"
                    :key="index"
                    class="image-item"
                  >
                    <img :src="image.url" alt="商品图片" class="uploaded-image" />
                    <div class="image-actions">
                      <button
                        type="button"
                        class="remove-btn"
                        @click="removeImage(index)"
                      >
                        ✕
                      </button>
                    </div>
                  </div>

                  <div class="add-image-btn" @click="$refs.imagesInput.click()">
                    <i class="icon">➕</i>
                    <p>添加图片</p>
                  </div>
                </div>

                <input
                  type="file"
                  ref="imagesInput"
                  @change="handleImagesUpload"
                  accept="image/*"
                  multiple
                  style="display: none"
                />

                <div class="upload-tips">
                  <p>• 最多可上传9张图片</p>
                  <p>• 支持JPG、PNG格式</p>
                  <p>• 建议图片尺寸：800x800px</p>
                </div>
              </div>
            </div>

            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="closeModal">
                取消
              </button>
              <button type="submit" class="submit-btn" :disabled="submitting">
                {{ submitting ? '保存中...' : (isEditing ? '更新' : '添加') }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 规格管理模态框 -->
    <div v-if="showSkuModal" class="modal-overlay" @click="closeSkuModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>管理商品规格 - {{ currentProductName }}</h2>
          <button class="close-btn" @click="closeSkuModal">✕</button>
        </div>

        <div class="modal-body">
          <!-- 添加规格表单 -->
          <form @submit.prevent="submitSku" class="sku-form">
            <h3>添加新规格</h3>

            <div class="form-row">
              <div class="form-group">
                <label>规格名称 *</label>
                <input
                  v-model="skuForm.name"
                  type="text"
                  required
                  placeholder="例如：红色-L码"
                  class="form-input"
                />
              </div>

              <div class="form-group">
                <label>价格 *</label>
                <input
                  v-model="skuForm.price"
                  type="number"
                  step="0.01"
                  min="0"
                  required
                  placeholder="0.00"
                  class="form-input"
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>库存 *</label>
                <input
                  v-model="skuForm.stock"
                  type="number"
                  min="0"
                  required
                  placeholder="0"
                  class="form-input"
                />
              </div>

              <div class="form-group">
                <label>状态</label>
                <select v-model="skuForm.status" class="form-select">
                  <option value="1">启用</option>
                  <option value="0">禁用</option>
                </select>
              </div>
            </div>

            <div class="form-actions">
              <button type="submit" class="submit-btn">
                添加规格
              </button>
            </div>
          </form>

          <!-- 规格列表 -->
          <div class="sku-list" v-if="skuList.length > 0">
            <h3>已添加的规格</h3>
            <div class="sku-table">
              <div class="sku-header">
                <div>规格名称</div>
                <div>价格</div>
                <div>库存</div>
                <div>状态</div>
                <div>操作</div>
              </div>
              <div v-for="(sku, index) in skuList" :key="index" class="sku-row">
                <div>{{ sku.name }}</div>
                <div>¥{{ sku.price }}</div>
                <div>{{ sku.stock }}</div>
                <div>
                  <span :class="sku.status === 1 ? 'status-active' : 'status-inactive'">
                    {{ sku.status === 1 ? '启用' : '禁用' }}
                  </span>
                </div>
                <div>
                  <button @click="removeSku(index)" class="remove-btn">删除</button>
                </div>
              </div>
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="cancel-btn" @click="closeSkuModal">
              关闭
            </button>
            <button
              type="button"
              class="submit-btn"
              @click="saveAllSkus"
              :disabled="skuList.length === 0"
            >
              保存所有规格
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 规格管理模态框 -->
    <div v-if="showSkuManageModal" class="modal-overlay" @click="closeSkuManageModal">
      <div class="modal-content sku-manage-modal" @click.stop>
        <div class="modal-header">
          <h3>规格管理 - {{ currentManageProduct?.productName }}</h3>
          <button class="close-btn" @click="closeSkuManageModal">×</button>
        </div>

        <div class="modal-body">
          <div v-if="existingSkuList.length === 0" class="empty-sku-state">
            <div class="empty-icon">📋</div>
            <p>该商品暂无规格信息</p>
          </div>

          <div v-else class="sku-manage-list">
            <div class="sku-manage-header">
              <div>规格名称</div>
              <div>价格</div>
              <div>库存</div>
              <div>销量</div>
              <div>状态</div>
              <div>操作</div>
            </div>

            <div v-for="sku in existingSkuList" :key="sku.id" class="sku-manage-row">
              <div class="sku-field">
                <input
                  v-if="editingSkuId === sku.id"
                  v-model="sku.name"
                  type="text"
                  class="sku-input"
                  placeholder="规格名称"
                />
                <span v-else class="sku-text">{{ sku.name }}</span>
              </div>

              <div class="sku-field">
                <input
                  v-if="editingSkuId === sku.id"
                  v-model="sku.price"
                  type="number"
                  step="0.01"
                  class="sku-input"
                  placeholder="价格"
                />
                <span v-else class="sku-text">¥{{ sku.price }}</span>
              </div>

              <div class="sku-field">
                <input
                  v-if="editingSkuId === sku.id"
                  v-model="sku.stock"
                  type="number"
                  class="sku-input"
                  placeholder="库存"
                />
                <span v-else class="sku-text">{{ sku.stock }}</span>
              </div>

              <div class="sku-field">
                <span class="sku-text">{{ sku.sale || 0 }}</span>
              </div>

              <div class="sku-field">
                <select
                  v-if="editingSkuId === sku.id"
                  v-model="sku.status"
                  class="sku-select"
                >
                  <option :value="1">启用</option>
                  <option :value="0">禁用</option>
                </select>
                <span v-else :class="sku.status === 1 ? 'status-active' : 'status-inactive'">
                  {{ sku.status === 1 ? '启用' : '禁用' }}
                </span>
              </div>

              <div class="sku-actions">
                <button
                  v-if="editingSkuId === sku.id"
                  @click="saveSkuEdit(sku)"
                  class="save-btn"
                >
                  保存
                </button>
                <button
                  v-if="editingSkuId === sku.id"
                  @click="cancelSkuEdit"
                  class="cancel-edit-btn"
                >
                  取消
                </button>
                <button
                  v-else
                  @click="editSku(sku)"
                  class="edit-sku-btn"
                >
                  编辑
                </button>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" class="cancel-btn" @click="closeSkuManageModal">
            关闭
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 商品详情查看/编辑模态框 -->
  <div v-if="showProductViewModal" class="modal-overlay" @click="closeProductViewModal">
    <div class="modal-content product-view-modal" @click.stop>
      <div class="modal-header">
        <h3>{{ isEditMode ? '编辑商品' : '商品详情' }}</h3>
        <button class="close-btn" @click="closeProductViewModal">×</button>
      </div>

      <div class="modal-body">
        <div class="product-detail-container">
          <!-- 商品基本信息 -->
          <div class="product-basic-info">
            <div class="product-image-section">
              <!-- 主图片 -->
              <div class="main-image">
                <img :src="isEditMode ? editableProductDetail.image : productDetail.image"
                     :alt="isEditMode ? editableProductDetail.name : productDetail.name"
                     @click="isEditMode && triggerMainImageUpload()"
                     :style="{ cursor: isEditMode ? 'pointer' : 'default' }" />
                <div v-if="isEditMode" class="image-overlay">
                  <input type="file" @change="handleMainImageUpload" accept="image/*" class="file-input" id="mainImageInput" ref="mainImageInput">
                </div>
              </div>

              <!-- 图片库 -->
              <div v-if="(isEditMode ? editableProductDetail.productImages : productDetail.productImages) &&
                         (isEditMode ? editableProductDetail.productImages : productDetail.productImages).length > 0"
                   class="image-gallery">
                <div
                  v-for="(image, index) in (isEditMode ? editableProductDetail.productImages : productDetail.productImages)"
                  :key="image.id || index"
                  class="gallery-item"
                  :class="{ 'editable': isEditMode }"
                >
                  <img :src="image.url"
                       :alt="isEditMode ? editableProductDetail.name : productDetail.name"
                       @click="isEditMode && triggerSubImageUpload(index)"
                       :style="{ cursor: isEditMode ? 'pointer' : 'default' }" />
                  <div v-if="isEditMode" class="image-overlay">
                    <input
                      type="file"
                      @change="(event) => handleSubImageUpload(event, index)"
                      accept="image/*"
                      class="file-input"
                      :id="'subImageInput' + index"
                      :ref="'subImageInput' + index"
                    >
                  </div>
                  <!-- 删除按钮 -->
                  <div v-if="isEditMode" class="image-actions">
                    <button 
                      class="remove-btn" 
                      @click="deleteProductImage(image.id)"
                      title="删除图片"
                    >
                      ×
                    </button>
                  </div>
                </div>
                <div v-if="isEditMode" class="add-image-item">
                  <input type="file" @change="handleAdditionalImageUpload" accept="image/*" class="file-input" id="additionalImageInput">
                  <label for="additionalImageInput" class="add-image-btn">
                    <i class="icon">+</i>
                    添加图片
                  </label>
                </div>
              </div>

              <!-- 编辑模式下的图片添加区域 -->
              <div v-if="isEditMode && (!editableProductDetail.productImages || editableProductDetail.productImages.length === 0)"
                   class="image-gallery">
                <div class="add-image-item">
                  <input type="file" @change="handleAdditionalImageUpload" accept="image/*" class="file-input" id="additionalImageInput">
                  <label for="additionalImageInput" class="add-image-btn">
                    <i class="icon">+</i>
                    添加图片
                  </label>
                </div>
              </div>
            </div>

            <div class="product-info-section">
              <!-- 商品名称 -->
              <div class="form-group">
                <label v-if="isEditMode">商品名称</label>
                <h2 v-if="!isEditMode" class="product-name">{{ productDetail.name }}</h2>
                <input
                  v-if="isEditMode"
                  type="text"
                  v-model="editableProductDetail.name"
                  class="edit-input product-name-input"
                  placeholder="请输入商品名称"
                />
              </div>

              <!-- 商品价格 -->
              <div class="form-group">
                <label v-if="isEditMode">商品价格</label>
                <div v-if="!isEditMode" class="product-price">¥{{ productDetail.price }}</div>
                <div v-if="isEditMode" class="price-input-group">
                  <span class="currency">¥</span>
                  <input
                    type="number"
                    v-model="editableProductDetail.price"
                    class="edit-input price-input disabled"
                    placeholder="0.00"
                    min="0"
                    step="0.01"
                    disabled
                  />
                </div>
              </div>

              <!-- 商品分类 -->
              <div class="form-group">
                <label v-if="isEditMode">商品分类</label>
                <div v-if="!isEditMode" class="product-category">
                  <span class="category-label">分类：</span>
                  <span class="category-name">{{ productDetail.categoryName || '未分类' }}</span>
                </div>
                <div v-if="isEditMode" class="category-select-group">
                  <select
                    v-model="editableProductDetail.categoryId"
                    class="edit-select category-select"
                    :disabled="loadingCategories"
                  >
                    <option
                      v-for="category in categoryList"
                      :key="category.id"
                      :value="category.id"
                    >
                      {{ category.name }}
                    </option>
                  </select>
                  <span v-if="loadingCategories" class="loading-text">加载中...</span>
                </div>
              </div>

              <!-- 商品统计信息 -->
              <div v-if="!isEditMode" class="product-stats">
                <div class="stat-item">
                  <span class="label">库存：</span>
                  <span class="value">{{ productDetail.stock }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">浏览量：</span>
                  <span class="value">{{ productDetail.viewCount }}</span>
                </div>
              </div>

              <!-- 库存编辑 -->
              <div v-if="isEditMode" class="form-group">
                <label>库存数量</label>
                <input
                  type="number"
                  v-model="editableProductDetail.stock"
                  class="edit-input disabled"
                  placeholder="请输入库存数量"
                  min="0"
                  disabled
                />
              </div>

              <!-- 商品描述 -->
              <div class="form-group">
                <label v-if="isEditMode">商品描述</label>
                <h4 v-if="!isEditMode">商品描述</h4>
                <p v-if="!isEditMode">{{ productDetail.description }}</p>
                <textarea
                  v-if="isEditMode"
                  v-model="editableProductDetail.description"
                  class="edit-textarea"
                  placeholder="请输入商品描述"
                  rows="4"
                ></textarea>
              </div>
            </div>
          </div>

          <!-- 店铺信息 (仅查看模式显示) -->
          <div v-if="!isEditMode" class="shop-info-section">
            <h4>店铺信息</h4>
            <div class="shop-details">
              <div class="shop-logo">
                <img :src="productDetail.logoUrl" :alt="productDetail.shopName" />
              </div>
              <div class="shop-info">
                <div class="shop-name">{{ productDetail.shopName }}</div>
                <div class="shop-address">地址：{{ productDetail.address }}</div>
                <div class="shop-phone">联系电话：{{ productDetail.contactPhone }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <div class="footer-left">
          <button v-if="!isEditMode" type="button" class="cancel-btn" @click="closeProductViewModal">
            关闭
          </button>
          <button v-if="isEditMode" type="button" class="cancel-btn" @click="cancelEdit">
            取消
          </button>
        </div>
        <div class="footer-right">
          <button v-if="!isEditMode" type="button" class="edit-btn" @click="enterEditMode">
            修改商品
          </button>
          <button v-if="isEditMode" type="button" class="submit-btn" @click="saveProductChanges" :disabled="editSubmitting">
            {{ editSubmitting ? '保存中...' : '保存修改' }}
          </button>
        </div>
      </div>
    </div>
  </div>


</template>

<script>
import * as XLSX from 'xlsx';
import {
  getProductList,
  addProduct,
  updateProduct,
  // getProductMessageById,
  getSellerCategory,
  getPublicCategory,
  getSkusByProductId,
  addProductSku,
  updateProductSku,
  getProductDetail,
  uploadProductImage,
  updateProductStatus
} from '@/api/user'

import { deleteProductImage } from '../api/seller';

export default {
  name: 'SellerProductManage',
  data() {
    return {
      // 商品列表数据
      productList: [],
      loading: false,

      // 搜索和筛选
      searchKeyword: '',
      statusFilter: '',

      // 分页
      currentPage: 1,
      pageSize: 10,
      totalItems: 0,
      totalPages: 0,

      // 模态框
      showModal: false,
      isEditing: false,
      submitting: false,

      // 商品表单
      productForm: {
        id: null,
        sellerId: null,
        productName: '',
        productDescription: '',
        productImage: '',
        categoryId: null,
        productImages: []
      },

      // 分类列表
      categoryList: [],
      loadingCategories: false,

      // 图片上传相关
      uploadedImages: [],
      mainImageIndex: 0,

      // 规格管理相关
      showSkuModal: false,
      currentProductId: null,
      currentProductName: '',
      skuForm: {
        productId: null,
        name: '',
        price: '',
        stock: '',
        status: 1 // 1: 启用, 0: 禁用
      },
      skuList: [],

      // 规格查看管理相关
      showSkuManageModal: false,
      currentManageProduct: null,
      existingSkuList: [],
      editingSkuId: null,

      // 商品详情查看相关
      showProductViewModal: false,
      isEditMode: false, // 是否处于编辑模式
      editableProductDetail: {}, // 可编辑的商品详情副本
      productDetail: {
        id: null,
        name: '',
        description: '',
        price: 0,
        stock: 0,
        viewCount: 0,
        image: '',
        sellerId: '',
        shopName: '',
        logoUrl: '',
        address: '',
        contactPhone: '',
        productImages: [],
        categoryId: null,
        categoryName: ''
      },

      // 商品修改相关
      editSubmitting: false
    }
  },
  computed: {
    visiblePages() {
      const pages = []
      const start = Math.max(1, this.currentPage - 2)
      const end = Math.min(this.totalPages, this.currentPage + 2)

      for (let i = start; i <= end; i++) {
        pages.push(i)
      }

      return pages
    },

    sellerId() {
      return localStorage.getItem('sellerId') || 1
    }
  },
  watch: {
    // 监听编辑模式下分类ID的变化
    'editableProductDetail.categoryId'(newVal, oldVal) {
      console.log('🔄 分类ID变化:', { 
        oldVal, 
        newVal, 
        isEditMode: this.isEditMode,
        matchedCategory: this.categoryList.find(cat => cat.id === newVal)
      })
    }
  },
  mounted() {
    this.loadProductList()
    this.loadCategoryList()
  },
    methods: {
    exportToExcel() {
      const data = this.productList.map(product => ({
        '商品ID': product.productId,
        '商品名称': product.productName,
        '价格': product.productPrice,
        '库存': product.productStock,
        '状态': product.status === 1 ? '上架中' : '已下架',
        '创建时间': product.createTime,
        '更新时间': product.updateTime,
      }));

      const ws = XLSX.utils.json_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '商品列表');
      XLSX.writeFile(wb, '商品列表.xlsx');
    },
    // 加载商品列表
    async loadProductList() {
      this.loading = true
      try {
        // 基于API响应格式 {"total":8,"page":1,"size":10,"pages":1}
        // 调整请求参数以匹配后端预期
        const params = {
          pageNum: this.currentPage,
          size: parseInt(this.pageSize), // 使用size而不是pageSize
          sellerId: this.sellerId
        }
        


        if (this.searchKeyword) {
          params.keyword = this.searchKeyword
        }

        if (this.statusFilter !== '') {
          params.status = this.statusFilter
        }

        const response = await getProductList(params)
        
        // 适配API返回的数据格式: {"total":8,"page":1,"size":10,"pages":1}
        if (response) {
          // 处理返回的商品数据
          this.productList = response.list || []
          this.totalItems = response.total || 0
          this.totalPages = response.pages || Math.ceil(this.totalItems / this.pageSize)
          this.currentPage = response.page || this.currentPage
          
          // 不再根据API返回的size更新本地pageSize，以保持用户的选择
        }
      } catch (error) {
        console.error('加载商品列表失败:', error)
        this.$message?.error('加载商品列表失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadProductList()
    },

    // 刷新数据
    refreshData() {
      this.loadProductList()
    },

    // 分页
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page
        this.loadProductList()
      }
    },

    // 改变每页显示数量
    changePageSize() {
      // 确保pageSize是数字类型
      const newPageSize = parseInt(this.pageSize)

      
      // 验证pageSize值的有效性
      if (isNaN(newPageSize) || newPageSize <= 0) {
        console.error('无效的pageSize值:', newPageSize)
        return
      }
      
      this.pageSize = newPageSize
      // 重置到第一页
      this.currentPage = 1
      // 重新加载商品列表
      this.loadProductList()
    },

    // 显示添加模态框
    showAddModal() {
      this.isEditing = false
      this.resetForm()
      this.showModal = true
    },

    // 查看商品详情
    async viewProduct(product) {
      try {
        // 确保分类列表已加载（为编辑模式做准备）
        if (this.categoryList.length === 0) {
          await this.loadCategoryList()
        }

        const response = await getProductDetail(product.productId)
        this.productDetail = response
        this.showProductViewModal = true
      } catch (error) {
        console.error('获取商品详情失败:', error)
        this.$message?.error('获取商品详情失败: ' + error.message)
      }
    },

    // 关闭模态框
    closeModal() {
      this.showModal = false
      this.resetForm()
    },

    // 关闭商品详情模态框
    closeProductViewModal() {
      this.showProductViewModal = false
      this.isEditMode = false
      this.editableProductDetail = {}
      this.productDetail = {
        id: null,
        name: '',
        description: '',
        price: 0,
        stock: 0,
        viewCount: 0,
        image: '',
        sellerId: '',
        shopName: '',
        logoUrl: '',
        address: '',
        contactPhone: '',
        productImages: [],
        categoryId: null,
        categoryName: ''
      }
    },

    // 进入编辑模式
    async enterEditMode() {
      try {
        // 确保分类列表已加载
        if (this.categoryList.length === 0) {
          await this.loadCategoryList()
        }
        
        this.isEditMode = true
        
        // 如果商品有categoryName但没有categoryId，通过categoryName查找categoryId
        let categoryId = this.productDetail.categoryId
        
        if (!categoryId && this.productDetail.categoryName) {
          const matchedCategory = this.categoryList.find(cat => {
            // 去掉[公共]和[商家]前缀进行比较
            const cleanCategoryName = cat.name.replace(/^\[公共\]\s*|\[商家\]\s*/g, '').trim()
            const productCategoryName = this.productDetail.categoryName.trim()
            
            return cleanCategoryName === productCategoryName || cat.name === productCategoryName
          })
          
          if (matchedCategory) {
            categoryId = matchedCategory.id
          }
        }
        
        // 确保categoryId是有效的数字或null
        let finalCategoryId = null
        if (categoryId !== null && categoryId !== undefined && !isNaN(categoryId)) {
          finalCategoryId = parseInt(categoryId)
        }
        
        // 创建商品详情的可编辑副本
        const newEditableDetail = {
          id: this.productDetail.id,
          name: this.productDetail.name,
          price: this.productDetail.price,
          stock: this.productDetail.stock,
          description: this.productDetail.description,
          image: this.productDetail.image,
          status: this.productDetail.status || 1,
          categoryId: finalCategoryId,
          productImages: this.productDetail.productImages ? [...this.productDetail.productImages] : []
        }
        
        // Vue 3中直接赋值即可，无需$set
        this.editableProductDetail = newEditableDetail
      } catch (error) {
        console.error('进入编辑模式失败:', error)
        this.$message?.error('加载分类数据失败，请重试')
      }
    },

    // 取消编辑
    cancelEdit() {
      this.isEditMode = false
      this.editableProductDetail = {}
    },

    // 保存商品修改
    async saveProductChanges() {
      try {
        this.editSubmitting = true

        // 验证必填字段
        if (!this.editableProductDetail.name || !this.editableProductDetail.name.trim()) {
          this.$message?.error('请输入商品名称')
          return
        }

        // 构建更新数据
        const updateData = {
          productId: this.editableProductDetail.id,
          productName: this.editableProductDetail.name.trim(),
          productPrice: parseFloat(this.editableProductDetail.price),
          stock: parseInt(this.editableProductDetail.stock) || 0,
          productDescription: this.editableProductDetail.description || '',
          productImage: this.editableProductDetail.image || '',
          status: this.editableProductDetail.status || 1,
          categoryId: this.editableProductDetail.categoryId ? parseInt(this.editableProductDetail.categoryId) : null,
          productImages: (this.editableProductDetail.productImages || []).map(img => ({
            id: img.id || null,
            productId: this.editableProductDetail.id,
            url: img.url
          }))
        }



        await updateProduct(updateData)

        this.$message?.success('商品修改成功')

        // 更新本地数据
        Object.assign(this.productDetail, this.editableProductDetail)

        // 更新分类名称
        if (this.editableProductDetail.categoryId) {
          const selectedCategory = this.categoryList.find(cat => cat.id === this.editableProductDetail.categoryId)
          if (selectedCategory) {
            this.productDetail.categoryName = selectedCategory.name
          }
        } else {
          this.productDetail.categoryName = ''
        }

        // 退出编辑模式
        this.isEditMode = false
        this.editableProductDetail = {}

        // 重新加载商品列表
        this.loadProductList()

      } catch (error) {
        console.error('修改商品失败:', error)
        this.$message?.error('修改商品失败: ' + error.message)
      } finally {
        this.editSubmitting = false
      }
    },

    // 触发主图片上传
    triggerMainImageUpload() {
      this.$refs.mainImageInput.click()
    },

    // 删除商品图片
    async deleteProductImage(imageId) {
      try {
        if (!imageId) {
          // 如果没有imageId，说明是新添加但未保存的图片，直接从本地移除
          this.$message?.success('图片已从本地移除');
          this.editableProductDetail.productImages = this.editableProductDetail.productImages.filter(
            (img) => img.id !== imageId && img.url !== imageId // 假设imageId此时是url
          );
          this.productDetail.productImages = this.productDetail.productImages.filter(
            (img) => img.id !== imageId && img.url !== imageId // 假设imageId此时是url
          );
          return;
        }

        await deleteProductImage(imageId);
        this.$message?.success('图片删除成功');
        // 从本地数据中移除已删除的图片
        if (this.editableProductDetail.productImages) {
          this.editableProductDetail.productImages = this.editableProductDetail.productImages.filter(
            (img) => img.id !== imageId
          );
        }
        // 同时更新productDetail中的图片列表
        if (this.productDetail.productImages) {
          this.productDetail.productImages = this.productDetail.productImages.filter(
            (img) => img.id !== imageId
          );
        }
      } catch (error) {
        console.error('删除图片失败:', error);
        this.$message?.error('删除图片失败，请稍后再试');
      }
    },

    // 触发子图片上传
    triggerSubImageUpload(index) {
      const input = document.getElementById('subImageInput' + index)
      if (input) {
        input.click()
      }
    },

    // 处理主图片上传
    async handleMainImageUpload(event) {
      const file = event.target.files[0]
      if (file) {
        // 验证文件类型
        if (!file.type.startsWith('image/')) {
          this.$message?.error('请选择图片文件')
          event.target.value = ''
          return
        }

        // 验证文件大小 (限制为5MB)
        if (file.size > 5 * 1024 * 1024) {
          this.$message?.error('图片大小不能超过5MB')
          event.target.value = ''
          return
        }

        try {
          // 上传图片到服务器
          const imageUrl = await uploadProductImage(file)

          // 根据当前模式更新对应的数据
          if (this.isEditMode) {
            // 编辑模式：更新editableProductDetail
            this.editableProductDetail.image = imageUrl
          } else {
            // 添加模式：更新productForm
            this.productForm.productImage = imageUrl
          }
        } catch (error) {
          console.error('主图片上传失败:', error)
          this.$message?.error('主图片上传失败')
        }

        // 清空文件选择
        event.target.value = ''
      }
    },

    // 处理附加图片上传
    async handleAdditionalImageUpload(event) {
      const file = event.target.files[0]
      if (file) {
        // 验证文件类型
        if (!file.type.startsWith('image/')) {
          this.$message?.error('请选择图片文件')
          event.target.value = ''
          return
        }

        // 验证文件大小 (限制为5MB)
        if (file.size > 5 * 1024 * 1024) {
          this.$message?.error('图片大小不能超过5MB')
          event.target.value = ''
          return
        }

        // 检查图片数量限制
        const currentImages = this.editableProductDetail.productImages || []
        if (currentImages.length >= 9) {
          this.$message?.error('最多只能添加9张附加图片')
          event.target.value = ''
          return
        }

        try {
          // 上传图片到服务器
          const imageUrl = await uploadProductImage(file)

          if (!this.editableProductDetail.productImages) {
            this.editableProductDetail.productImages = []
          }
          this.editableProductDetail.productImages.push({
            id: null, // 新图片ID为null，后端会自动生成
            productId: this.editableProductDetail.id,
            url: imageUrl
          })
          this.$message?.success('图片已添加，记得保存修改')
        } catch (error) {
          console.error('附加图片上传失败:', error)
          this.$message?.error('附加图片上传失败')
        }

        // 清空文件输入
        event.target.value = ''
      }
    },


    // 处理子图更换
    async handleSubImageUpload(event, index) {
      const file = event.target.files[0]
      if (!file) return

      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        this.$message?.error('请选择图片文件')
        event.target.value = ''
        return
      }

      // 验证文件大小（5MB）
      if (file.size > 5 * 1024 * 1024) {
        this.$message?.error('图片大小不能超过5MB')
        event.target.value = ''
        return
      }

      try {
        // 上传图片到服务器
        const imageUrl = await uploadProductImage(file)

        if (this.editableProductDetail.productImages && this.editableProductDetail.productImages[index]) {
          // 更新指定索引的图片
          this.editableProductDetail.productImages[index].url = imageUrl
          this.$message?.success('图片已更换，记得保存修改')
        }
      } catch (error) {
        console.error('子图更换失败:', error)
        this.$message?.error('子图更换失败')
      }

      // 清空文件输入
      event.target.value = ''
    },

    // 重置表单
    resetForm() {
      this.productForm = {
        id: null,
        sellerId: this.sellerId,
        productName: '',
        productDescription: '',
        productImage: '',
        categoryId: null,
        productImages: []
      }
      this.uploadedImages = []
      this.mainImageIndex = 0
    },

    // 提交商品
    async submitProduct() {
      // 表单验证
      if (!this.validateForm()) {
        return
      }

      this.submitting = true
      try {
        const productData = {
          sellerId: parseInt(this.productForm.sellerId || this.sellerId),
          productName: this.productForm.productName,
          productDescription: this.productForm.productDescription,
          productImage: this.productForm.productImage,
          categoryId: parseInt(this.productForm.categoryId),
          productImages: this.productForm.productImages // 已包含正确的ProductImagesCreateDTO格式
        }



        if (this.isEditing) {
          productData.id = this.productForm.id
          await updateProduct(productData)
          this.$message?.success('商品更新成功')
        } else {
          const result = await addProduct(productData)

          // 获取后端返回的商品ID
          const newProductId = result.data || result

          this.$message?.success('商品添加成功')

          // 添加商品成功后，提示用户添加规格
          setTimeout(() => {
            if (confirm('商品添加成功！需要添加规格才能上架销售，是否立即添加规格？')) {
              this.currentProductId = newProductId
              this.currentProductName = this.productForm.productName
              this.showSkuModal = true
            }
          }, 500)
        }

        this.closeModal()
        this.loadProductList()
      } catch (error) {
        console.error('保存商品失败:', error)
        this.$message?.error('保存商品失败')
      } finally {
        this.submitting = false
      }
    },

    // 商品图片集上传
    async handleImagesUpload(event) {
      const files = Array.from(event.target.files)
      if (!files.length) return

      // 检查图片数量限制
      if (this.uploadedImages.length + files.length > 9) {
        this.$message?.error('最多只能上传9张图片')
        return
      }

      for (const file of files) {
        // 验证文件类型
        if (!file.type.startsWith('image/')) {
          this.$message?.error(`文件 ${file.name} 不是图片格式`)
          continue
        }

        // 验证文件大小 (5MB)
        if (file.size > 5 * 1024 * 1024) {
          this.$message?.error(`图片 ${file.name} 大小不能超过5MB`)
          continue
        }

        try {
          const imageUrl = await uploadProductImage(file)
          this.uploadedImages.push({
            url: imageUrl,
            name: file.name
          })
        } catch (error) {
          console.error(`图片 ${file.name} 上传失败:`, error)
          this.$message?.error(`图片 ${file.name} 上传失败`)
        }
      }

      // 更新productImages数组
      this.updateProductImages()

      // 清空input
      event.target.value = ''
    },

    // 移除图片
    // 合并后的 removeImage 方法（用于编辑模式下删除附加图片）
    removeImage(index) {
      if (this.isEditMode && this.editableProductDetail.productImages) {
        if (confirm('确定要删除这张图片吗？')) {
          this.editableProductDetail.productImages.splice(index, 1)
          this.$message?.success('图片已删除，记得保存修改')
        }
      } else if (!this.isEditMode && this.uploadedImages) {
        this.uploadedImages.splice(index, 1)
        this.updateProductImages()
      }
    },

    // 更新productImages数组
    updateProductImages() {
      this.productForm.productImages = this.uploadedImages.map(image => ({
        productId: null, // 后端会处理，上传时为空
        url: image.url
      }))
    },

    // 表单验证
    validateForm() {
      if (!this.productForm.productName.trim()) {
        this.$message?.error('请输入商品名称')
        return false
      }

      if (!this.productForm.productDescription.trim()) {
        this.$message?.error('请输入商品描述')
        return false
      }

      if (!this.productForm.categoryId) {
        this.$message?.error('请选择商品分类')
        return false
      }

      if (!this.productForm.productImage) {
        this.$message?.error('请上传主图片')
        return false
      }

      return true
    },

    // 加载分类列表
    async loadCategoryList() {
      this.loadingCategories = true
      try {
        // 同时获取公共分类和商家分类
        const [publicCategoryResponse, sellerCategoryResponse] = await Promise.all([
          getPublicCategory(),
          getSellerCategory(this.sellerId)
        ])

        // 处理公共分类
        const publicCategories = publicCategoryResponse.map(category => ({
          id: parseInt(category.categoryId), // 确保ID为数字类型
          name: `[公共] ${category.categoryName}`
        }))

        // 处理商家分类
        const sellerCategories = sellerCategoryResponse.map(category => ({
          id: parseInt(category.categoryId), // 确保ID为数字类型
          name: `[商家] ${category.categoryName}`
        }))

        // 合并分类列表，先显示公共分类，再显示商家分类
        this.categoryList = [...publicCategories, ...sellerCategories]
        
        // 去重处理，避免ID重复
        const uniqueIds = new Set()
        this.categoryList = this.categoryList.filter(category => {
          if (uniqueIds.has(category.id)) {
            return false
          }
          uniqueIds.add(category.id)
          return true
        })
      } catch (error) {
        console.error('加载分类列表失败:', error)
        this.$message?.error('加载分类列表失败')

        // 如果API调用失败，使用备用的模拟数据
        this.categoryList = [
          { id: 1, name: '[公共] 电子产品' },
          { id: 2, name: '[公共] 服装鞋帽' },
          { id: 3, name: '[公共] 家居用品' },
          { id: 4, name: '[公共] 美妆护肤' },
          { id: 5, name: '[公共] 运动户外' },
          { id: 6, name: '[商家] 图书音像' },
          { id: 7, name: '[商家] 食品饮料' },
          { id: 8, name: '[商家] 母婴用品' }
        ]
      } finally {
        this.loadingCategories = false
      }
    },

    // 切换商品状态
    async toggleProductStatus(product) {
      try {
        // 这里需要调用实际的API
        console.log('切换商品状态:', product.productId, product.status === 1 ? 0 : 1)

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))

        product.status = product.status === 1 ? 0 : 1
        this.$message?.success(product.status === 1 ? '商品已上架' : '商品已下架')
      } catch (error) {
        console.error('状态切换失败:', error)
        this.$message?.error('状态切换失败')
      }
    },



    // 格式化价格
    formatPrice(price) {
      return parseFloat(price || 0).toFixed(2)
    },



    // 智能检查图片URL是否有效，避免无效请求
    getImageSrc(productImage) {
      // 默认占位图片
      const defaultImage = '/placeholder-product.png'

      // 基础检查：空值、非字符串、空字符串
      if (!productImage || typeof productImage !== 'string' || productImage.trim() === '') {
        return defaultImage
      }

      const trimmedUrl = productImage.trim()

      // 检查明显的测试/虚假数据
      const invalidPatterns = [
        'example.com',
        'placeholder',
        'fake',
        'test.com',
        'demo.com',
        'sample.com',
        'mock.com',
        'dummy.com',
        'lorem',
        'ipsum',
        '`',
        '{{',
        '}}',
        'null',
        'undefined',
        'N/A',
        'n/a',
        'no-image',
        'noimage',
        'default.jpg',
        'default.png',
        'temp.jpg',
        'temp.png'
      ]

      // 检查是否包含无效模式
      for (const pattern of invalidPatterns) {
        if (trimmedUrl.toLowerCase().includes(pattern.toLowerCase())) {
          return defaultImage
        }
      }

      // 检查特定的测试域名
      const testDomains = [
        'http://example',
        'https://example',
        'http://test',
        'https://test',
        'http://demo',
        'https://demo',
        'http://fake',
        'https://fake'
      ]

      for (const domain of testDomains) {
        if (trimmedUrl.toLowerCase().startsWith(domain.toLowerCase())) {
          return defaultImage
        }
      }

      // 对于HTTP/HTTPS URL，进行URL格式验证
      if (trimmedUrl.startsWith('http://') || trimmedUrl.startsWith('https://')) {
        try {
          const url = new URL(trimmedUrl)

          // 检查域名是否为明显的测试域名
          const hostname = url.hostname.toLowerCase()
          if (hostname.includes('example') ||
              hostname.includes('test') ||
              hostname.includes('fake') ||
              hostname.includes('demo') ||
              hostname.includes('localhost') ||
              hostname === '127.0.0.1' ||
              hostname === '0.0.0.0') {
            return defaultImage
          }

          // 检查文件扩展名是否为图片格式
          const pathname = url.pathname.toLowerCase()
          const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg', '.bmp']
          const hasImageExtension = imageExtensions.some(ext => pathname.endsWith(ext))

          // 如果没有图片扩展名且路径不像图片路径，返回默认图片
          if (!hasImageExtension && !pathname.includes('image') && !pathname.includes('photo') && !pathname.includes('pic')) {
            return defaultImage
          }

          return trimmedUrl
        } catch  {
          // URL格式无效
          return defaultImage
        }
      }

      // 对于相对路径，检查是否看起来像有效的图片路径
      if (trimmedUrl.startsWith('/') || trimmedUrl.startsWith('./') || trimmedUrl.startsWith('../')) {
        const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg', '.bmp']
        const hasImageExtension = imageExtensions.some(ext => trimmedUrl.toLowerCase().endsWith(ext))

        if (hasImageExtension) {
          return trimmedUrl
        } else {
          return defaultImage
        }
      }

      // 其他情况，如果看起来不像有效的图片URL，返回默认图片
      return defaultImage
    },

    // ===== 规格管理相关方法 =====

    // 关闭规格模态框
    closeSkuModal() {
      this.showSkuModal = false
      this.resetSkuForm()
      this.skuList = []
    },

    // 重置规格表单
    resetSkuForm() {
      this.skuForm = {
        productId: this.currentProductId,
        name: '',
        price: '',
        stock: '',
        status: 1
      }
    },

    // 提交规格表单
    async submitSku() {
      // 验证表单
      if (!this.skuForm.name.trim()) {
        this.$message?.error('请输入规格名称')
        return
      }

      if (!this.skuForm.price || this.skuForm.price <= 0) {
        this.$message?.error('请输入有效的价格')
        return
      }

      if (!this.skuForm.stock || this.skuForm.stock < 0) {
        this.$message?.error('请输入有效的库存')
        return
      }

      try {
        // 调用API添加规格
        const skuData = {
          productId: this.currentProductId,
          name: this.skuForm.name.trim(),
          price: parseFloat(this.skuForm.price),
          stock: parseInt(this.skuForm.stock),
          status: parseInt(this.skuForm.status)
        }

        await addProductSku(skuData)

        // 添加到本地规格列表显示
        const newSku = {
          productId: this.currentProductId,
          name: this.skuForm.name.trim(),
          price: parseFloat(this.skuForm.price),
          stock: parseInt(this.skuForm.stock),
          status: parseInt(this.skuForm.status)
        }

        this.skuList.push(newSku)
        this.$message?.success('规格添加成功')
        this.resetSkuForm()
      } catch (error) {
        console.error('添加规格失败:', error)
        this.$message?.error('添加规格失败: ' + (error.message || '未知错误'))
      }
    },

    // 删除规格
    removeSku(index) {
      if (confirm('确定要删除这个规格吗？')) {
        this.skuList.splice(index, 1)
        this.$message?.success('规格删除成功')
      }
    },

    // 保存所有规格
    async saveAllSkus() {
      if (this.skuList.length === 0) {
        this.$message?.error('请至少添加一个规格')
        return
      }

      try {
        // 这里后续会调用实际的API


        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        this.$message?.success(`成功保存 ${this.skuList.length} 个规格`)
        this.closeSkuModal()
        this.loadProductList() // 刷新商品列表
      } catch (error) {
        console.error('保存规格失败:', error)
        this.$message?.error('保存规格失败')
      }
    },

    // 规格管理相关方法
    // 打开添加规格表单
    showAddSkuForm(product) {
      this.currentProductId = product.productId
      this.currentProductName = product.productName
      this.showSkuModal = true
      this.resetSkuForm()
    },



    // 打开规格管理模态框
    async manageProductSku(product) {
      this.currentManageProduct = product
      this.showSkuManageModal = true
      this.editingSkuId = null

      try {
        // 调用API获取商品的规格列表
        const response = await getSkusByProductId(product.productId)
        this.existingSkuList = response || []
      } catch (error) {
        console.error('获取规格列表失败:', error)
        this.$message?.error('获取规格列表失败')
        this.existingSkuList = []
      }
    },

    // 关闭规格管理模态框
    closeSkuManageModal() {
      this.showSkuManageModal = false
      this.currentManageProduct = null
      this.existingSkuList = []
      this.editingSkuId = null
    },

    // 编辑规格
    editSku(sku) {
      // 保存原始数据，用于取消编辑时恢复
      this.originalSkuData = { ...sku }
      this.editingSkuId = sku.id
    },

    // 取消编辑规格
    cancelSkuEdit() {
      if (this.originalSkuData) {
        // 恢复原始数据
        const index = this.existingSkuList.findIndex(sku => sku.id === this.editingSkuId)
        if (index !== -1) {
          this.existingSkuList[index] = { ...this.originalSkuData }
        }
      }
      this.editingSkuId = null
      this.originalSkuData = null
    },

    // 保存规格编辑
    async saveSkuEdit(sku) {
      // 验证数据
      if (!sku.name || !sku.name.trim()) {
        this.$message?.error('规格名称不能为空')
        return
      }

      if (!sku.price || sku.price <= 0) {
        this.$message?.error('价格必须大于0')
        return
      }

      if (!sku.stock || sku.stock < 0) {
        this.$message?.error('库存不能为负数')
        return
      }

      try {
        // 调用更新API
        const updateData = {
          id: sku.id,
          productId: sku.productId,
          name: sku.name.trim(),
          price: parseFloat(sku.price),
          stock: parseInt(sku.stock),
          status: parseInt(sku.status)
        }

        await updateProductSku(updateData)

        this.$message?.success('规格更新成功')
        this.editingSkuId = null
        this.originalSkuData = null

        // 重新加载规格列表
        await this.manageProductSku(this.currentManageProduct)
      } catch (error) {
        console.error('更新规格失败:', error)
        this.$message?.error('更新规格失败')
      }
    },

    // 更新商品状态（上下架）
    async updateProductStatus(productId, status) {
      try {
        console.log('更新商品状态:', productId, status)
        
        // 调用API更新商品状态
        await updateProductStatus(productId, status)
        
        // 更新本地商品列表中的状态
        const product = this.productList.find(p => p.productId === productId)
        if (product) {
          product.status = status
        }
        
        // 显示成功消息
        this.$message?.success(status === 1 ? '商品已上架' : '商品已下架')
        
      } catch (error) {
        console.error('更新商品状态失败:', error)
        this.$message?.error('更新商品状态失败')
      }
    }
  }
}
</script>

<style scoped>
.seller-product-manage {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
 
  overflow: hidden;
}

.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  box-sizing: border-box;
}

.content-header {
  margin-bottom: 30px;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
  position: relative;
  overflow: hidden;
}

.content-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
  opacity: 0.3;
}

.content-header h1 {
  font-size: 32px;
  color: white;
  margin: 0 0 12px 0;
  font-weight: 700;
  position: relative;
  z-index: 1;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.content-header p {
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  font-size: 16px;
  position: relative;
  z-index: 1;
  opacity: 0.95;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding: 25px 30px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
  border: 1px solid rgba(0,0,0,0.05);
  backdrop-filter: blur(10px);
  position: relative;
}



.search-section {
  display: flex;
  gap: 20px;
  align-items: center;
}

.search-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  width: 280px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.search-btn, .refresh-btn, .add-btn {
  padding: 12px 20px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.search-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.search-btn:active {
  transform: translateY(0);
}

.refresh-btn {
  background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
}

.refresh-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 2px 8px rgba(108, 117, 125, 0.2);
}

.add-btn {
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(40, 167, 69, 0.4);
}

.add-btn:active {
  transform: translateY(0);
}

.action-section {
  display: flex;
  gap: 15px;
  align-items: center;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-filter {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  background: #f8f9fa;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 120px;
}

.status-filter:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.product-list {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

.list-header {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 2fr 1fr 1fr;
  gap: 20px;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  font-weight: 600;
  color: #495057;
}

.product-item {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 2fr 1fr 1fr;
  gap: 20px;
  padding: 20px;
  border-bottom: 1px solid #dee2e6;
  align-items: center;
}

.list-body {
  overflow-x: auto;
}

.product-item:hover {
  background: #f8f9fa;
}

.product-info {
  display: flex;
  gap: 15px;
  align-items: center;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e9ecef;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: opacity 0.3s ease;
}

.product-img {
  background-color: #f8f9fa;
}

.product-details h3 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.product-description {
  margin: 0 0 5px 0;
  color: #666;
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-id {
  font-size: 12px;
  color: #999;
}

.price {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #e74c3c;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.stock {
  font-size: 16px;
  font-weight: 600;
}

.low-stock {
  color: #e74c3c;
  margin-left: 19px;
}

.normal-stock {
  margin-left: 19px;
  color: #333;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  margin-left: 15px;
  font-weight: 500;
}

.status-badge.active {
  background: #d4edda;
  color: #155724;
}

.status-badge.inactive {
  background: #f8d7da;
  color: #721c24;
}

.actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.edit-btn {
  background: #007bff;
  color: white;
}

.status-btn.online {
  background: #28a745;
  color: white;
}

.status-btn.offline {
  background: #ffc107;
  color: #212529;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.add-sku-btn {
  background: #17a2b8;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.loading-state {
  text-align: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-btn, .page-number {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-number.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.page-info {
  margin-left: 20px;
  color: #666;
  font-size: 14px;
}

.page-size-selector {
  margin-left: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-selector label {
  color: #666;
  font-size: 14px;
}

.page-size-selector select {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #dee2e6;
}

.modal-header h2 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  font-size: 14px;
  background: #ffffff;
  transition: all 0.3s ease;
  outline: none;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  border-color: #3b82f6;
  background: #f8faff;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-group select {
  cursor: pointer;
  appearance: none;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
  background-position: right 12px center;
  background-repeat: no-repeat;
  background-size: 16px;
  padding-right: 40px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.image-upload {
  margin-top: 5px;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #007bff;
}

.preview-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 4px;
}

.upload-placeholder {
  color: #666;
}

.upload-placeholder .icon {
  font-size: 24px;
  margin-bottom: 10px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #dee2e6;
}

.cancel-btn {
  padding: 12px 24px;
  border: 2px solid #6b7280;
  background: white;
  color: #6b7280;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(107, 114, 128, 0.2);
}

.cancel-btn:hover {
  background: #6b7280;
  color: white;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(107, 114, 128, 0.3);
}

.submit-btn {
  padding: 10px 20px;
  border: none;
  background: #007bff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .main-content {
    margin-left: 0;
    padding: 10px;
  }

  .toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .search-section {
    flex-direction: column;
    gap: 10px;
  }

  .list-header,
  .product-item {
    grid-template-columns: 1fr;
    gap: 10px;
  }

  .form-row {
    grid-template-columns: 1fr;
  }
}

/* 图片上传样式 */
.main-image-upload {
  margin-top: 8px;
}

.upload-area {
  border: 2px dashed #d1d5db;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.upload-area:hover {
  border-color: #3b82f6;
  background: #eff6ff;
}

.main-upload {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.upload-placeholder .icon {
  font-size: 48px;
  color: #9ca3af;
}

.upload-placeholder p {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #374151;
}

.upload-tip {
  font-size: 14px;
  color: #6b7280;
}

.preview-image {
  max-width: 100%;
  max-height: 160px;
  border-radius: 8px;
  object-fit: cover;
}

.images-upload {
  margin-top: 8px;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.image-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e5e7eb;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 4px;
  right: 4px;
}

.remove-btn {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: none;
  background: rgba(239, 68, 68, 0.9);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  transition: all 0.2s ease;
}

.remove-btn:hover {
  background: #dc2626;
  transform: scale(1.1);
}

.add-image-btn {
  aspect-ratio: 1;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.add-image-btn:hover {
  border-color: #3b82f6;
  background: #eff6ff;
}

.add-image-btn .icon {
  font-size: 24px;
  color: #9ca3af;
  margin-bottom: 4px;
}

.add-image-btn p {
  margin: 0;
  font-size: 12px;
  color: #6b7280;
}

.upload-tips {
  background: #f3f4f6;
  border-radius: 8px;
  padding: 12px;
  border-left: 4px solid #3b82f6;
}

.upload-tips p {
  margin: 4px 0;
  font-size: 13px;
  color: #4b5563;
}

/* ===== 规格管理样式 ===== */
.sku-form {
  background: #f8fafc;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  border: 1px solid #e2e8f0;
}

.sku-form h3 {
  margin: 0 0 16px 0;
  color: #1e293b;
  font-size: 16px;
  font-weight: 600;
}

.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.form-row .form-group {
  flex: 1;
}

.sku-list {
  margin-top: 24px;
}

.sku-list h3 {
  margin: 0 0 16px 0;
  color: #1e293b;
  font-size: 16px;
  font-weight: 600;
}

.sku-table {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  overflow: hidden;
  background: white;
}

.sku-header {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 1fr;
  background: #f1f5f9;
  padding: 12px 16px;
  font-weight: 600;
  color: #475569;
  font-size: 14px;
  border-bottom: 1px solid #e2e8f0;
}

.sku-row {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 1fr;
  padding: 12px 16px;
  border-bottom: 1px solid #f1f5f9;
  align-items: center;
}

.sku-row:last-child {
  border-bottom: none;
}

.sku-row:hover {
  background: #f8fafc;
}

.status-active {
  color: #059669;
  font-weight: 500;
}

.status-inactive {
  color: #dc2626;
  font-weight: 500;
}

.remove-btn {
  background: #fee2e2;
  color: #dc2626;
  border: 1px solid #fecaca;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.remove-btn:hover {
  background: #fecaca;
  border-color: #f87171;
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  margin-top: 32px;
  padding: 24px 32px;
  background: #f8fafc;
  border-top: 2px solid #e2e8f0;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.05);
  min-height: 80px;
  position: relative;
  z-index: 10;
}

.modal-footer .submit-btn:disabled {
  background: #e2e8f0;
  color: #9ca3af;
  cursor: not-allowed;
}

.modal-footer .submit-btn:disabled:hover {
  background: #e2e8f0;
  transform: none;
}

.footer-left,
.footer-right {
  display: flex;
  gap: 12px;
  align-items: center;
  min-height: 40px;
}

.footer-right {
  justify-content: flex-end;
}

.footer-left button,
.footer-right button {
  position: relative;
  z-index: 11;
}

/* 商品详情模态框特定样式 */
.product-view-modal .modal-footer {
  background: #ffffff !important;
  border-top: 1px solid #e5e7eb;
  padding: 20px 24px;
  display: flex !important;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  position: sticky;
  bottom: 0;
  z-index: 1000;
  min-height: 60px;
  width: 100%;
  box-sizing: border-box;
}

.product-view-modal .cancel-btn {
  background: #f3f4f6 !important;
  color: #374151 !important;
  border: 1px solid #d1d5db !important;
  padding: 10px 20px !important;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-block !important;
  visibility: visible !important;
  opacity: 1 !important;
  position: relative !important;
  z-index: 1001 !important;
}

.product-view-modal .cancel-btn:hover {
  background: #e5e7eb;
  border-color: #9ca3af;
}

.product-view-modal .edit-btn {
  background: #3b82f6 !important;
  color: white !important;
  border: none !important;
  padding: 10px 20px !important;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-block !important;
  visibility: visible !important;
  opacity: 1 !important;
  position: relative !important;
  z-index: 1001 !important;
}

.product-view-modal .edit-btn:hover {
  background: #2563eb;
}

.product-view-modal .submit-btn {
  background: #10b981 !important;
  color: white !important;
  border: none !important;
  padding: 10px 20px !important;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-block !important;
  visibility: visible !important;
  opacity: 1 !important;
  position: relative !important;
  z-index: 1001 !important;
}

.product-view-modal .submit-btn:hover {
  background: #059669;
}

.product-view-modal .submit-btn:disabled {
  background: #9ca3af !important;
  cursor: not-allowed;
}

.product-view-modal .footer-left,
.product-view-modal .footer-right {
  display: flex !important;
  gap: 12px;
  align-items: center;
  visibility: visible !important;
  opacity: 1 !important;
  position: relative !important;
  z-index: 1001 !important;
}

.product-view-modal .footer-right {
  justify-content: flex-end;
}

/* 规格管理相关样式 */
.sku-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.sku-btn:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
  transform: translateY(-1px);
}

.sku-manage-modal {
  max-width: 900px;
  width: 90%;
}

.empty-sku-state {
  text-align: center;
  padding: 60px 20px;
  color: #64748b;
}

.empty-sku-state .empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-sku-state p {
  font-size: 16px;
  margin: 0;
}

.sku-manage-list {
  margin-top: 20px;
}

.sku-manage-header {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1.5fr;
  gap: 12px;
  padding: 12px 16px;
  background: #f8fafc;
  border-radius: 8px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.sku-manage-row {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1.5fr;
  gap: 12px;
  padding: 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  margin-bottom: 8px;
  align-items: center;
}

.sku-manage-row:hover {
  border-color: #cbd5e1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.sku-field {
  display: flex;
  align-items: center;
}

.sku-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.sku-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.sku-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  background: white;
  cursor: pointer;
}

.sku-text {
  font-size: 14px;
  color: #374151;
}

.sku-actions {
  display: flex;
  gap: 8px;
}

.edit-sku-btn {
  padding: 6px 12px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.edit-sku-btn:hover {
  background: #2563eb;
  transform: translateY(-1px);
}

.save-btn {
  padding: 6px 12px;
  background: #10b981;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.save-btn:hover {
  background: #059669;
  transform: translateY(-1px);
}

.cancel-edit-btn {
  padding: 6px 12px;
  background: #6b7280;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-edit-btn:hover {
  background: #4b5563;
  transform: translateY(-1px);
}

.status-active {
  color: #10b981;
  font-weight: 500;
}

.status-inactive {
  color: #ef4444;
  font-weight: 500;
}

/* 商品详情查看模态框样式 */
.product-view-modal {
  max-width: 1000px;
  max-height: 90vh;
  overflow: hidden;
  border-radius: 16px;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  animation: modalSlideUp 0.3s ease;
}

@keyframes modalSlideUp {
  from { 
    opacity: 0;
    transform: translateY(20px) scale(0.95);
  }
  to { 
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.product-detail-container {
  padding: 32px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  min-height: 100%;
  overflow-y: auto;
  max-height: calc(90vh - 140px);
}

.product-basic-info {
  display: flex;
  gap: 40px;
  margin-bottom: 40px;
  background: white;
  padding: 32px;
  border-radius: 16px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.product-image-section {
  flex: 1;
  max-width: 400px;
}

.main-image {
  width: 100%;
  margin-bottom: 20px;
  position: relative;
  overflow: hidden;
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.main-image img {
  width: 100%;
  height: 350px;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.main-image:hover img {
  transform: scale(1.05);
}

.image-gallery {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  padding: 16px;
  background: #f8fafc;
  border-radius: 12px;
}

.gallery-item {
  width: 90px;
  height: 90px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.gallery-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.gallery-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.gallery-item:hover img {
  transform: scale(1.1);
}

.product-info-section {
  flex: 1;
  padding-left: 20px;
}

.product-name {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 20px;
  line-height: 1.3;
  background: linear-gradient(135deg, #1f2937 0%, #374151 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.product-price {
  font-size: 36px;
  font-weight: 800;
  background: linear-gradient(135deg, #dc2626 0%, #ef4444 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.product-price::before {
  content: "¥";
  font-size: 24px;
  color: #dc2626;
}

.product-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.stat-item {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  padding: 16px;
  border-radius: 12px;
  text-align: center;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-item .label {
  color: #64748b;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 8px;
  display: block;
}

.stat-item .value {
  font-weight: 700;
  color: #1e293b;
  font-size: 18px;
  display: block;
}

.product-description {
  margin-top: 32px;
  background: white;
  padding: 24px;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.product-description h4 {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.product-description h4::before {
  content: "📝";
  font-size: 18px;
}

.product-description p {
  color: #4b5563;
  line-height: 1.8;
  font-size: 15px;
}

.shop-info-section {
  background: white;
  padding: 24px;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-top: 24px;
}

.shop-info-section h4 {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.shop-info-section h4::before {
  content: "🏪";
  font-size: 18px;
}

.shop-details {
  display: flex;
  gap: 20px;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 12px;
  border: 1px solid #e2e8f0;
}

.shop-logo {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease;
}

.shop-logo:hover {
  transform: scale(1.05);
}

.shop-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.shop-info {
  flex: 1;
}

.shop-name {
  font-size: 18px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 8px;
}

.shop-address,
.shop-phone {
  color: #64748b;
  font-size: 14px;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.shop-address::before {
  content: "📍";
  font-size: 12px;
}

.shop-phone::before {
  content: "📞";
  font-size: 12px;
}

/* 查看按钮样式 */
.view-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 600;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  display: flex;
  align-items: center;
  gap: 6px;
}

.view-btn:hover {
  background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(59, 130, 246, 0.4);
}



/* 编辑按钮样式 */
.edit-btn {
  background: linear-gradient(135deg, #10b981 0%, #047857 100%);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.edit-btn:hover {
  background: linear-gradient(135deg, #059669 0%, #065f46 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(16, 185, 129, 0.4);
}



.edit-btn .icon {
  font-size: 16px;
}

/* 商品修改模态框样式 */
.product-edit-modal {
  max-width: 700px;
  width: 95%;
  max-height: 90vh;
  overflow: hidden;
  border-radius: 16px;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  animation: modalSlideUp 0.3s ease;
}

.product-edit-modal .modal-body {
  padding: 32px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  overflow-y: auto;
  max-height: calc(90vh - 140px);
}

.product-edit-modal .form-group {
  margin-bottom: 24px;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

.product-edit-modal .form-group:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.product-edit-modal .form-group label {
  display: block;
  margin-bottom: 12px;
  font-weight: 700;
  color: #1f2937;
  font-size: 15px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.product-edit-modal .form-group input,
.product-edit-modal .form-group textarea,
.product-edit-modal .form-group select {
  width: 100%;
  padding: 14px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 10px;
  font-size: 15px;
  transition: all 0.3s ease;
  box-sizing: border-box;
  background: #f8fafc;
  font-weight: 500;
}

.product-edit-modal .form-group input:focus,
.product-edit-modal .form-group textarea:focus,
.product-edit-modal .form-group select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.15);
  background: white;
  transform: translateY(-1px);
}

.product-edit-modal .form-group textarea {
  resize: vertical;
  min-height: 100px;
  line-height: 1.6;
}

.product-edit-modal .submit-btn {
  background: linear-gradient(135deg, #10b981 0%, #047857 100%);
  color: white;
  border: none;
  padding: 14px 28px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
  display: flex;
  align-items: center;
  gap: 8px;
}

.product-edit-modal .submit-btn::before {
  content: "💾";
  font-size: 14px;
}

.product-edit-modal .submit-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #059669 0%, #065f46 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(16, 185, 129, 0.4);
}

.product-edit-modal .submit-btn:disabled {
  background: #9ca3af;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.product-edit-modal .cancel-btn {
  background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
  color: white;
  border: none;
  padding: 14px 28px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 600;
  margin-right: 16px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(107, 114, 128, 0.3);
  display: flex;
  align-items: center;
  gap: 8px;
}

.product-edit-modal .cancel-btn::before {
  content: "❌";
  font-size: 14px;
}

.product-edit-modal .cancel-btn:hover {
  background: linear-gradient(135deg, #4b5563 0%, #374151 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(107, 114, 128, 0.4);
}

/* 编辑模式样式 */
.product-info-section {
  position: relative;
  z-index: 3;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
  z-index: 3;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
}

.edit-input {
  width: 100%;
  padding: 12px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s ease;
  background: white;
}

.edit-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.edit-input:disabled {
  background-color: #f3f4f6;
  color: #9ca3af;
  cursor: not-allowed;
  border-color: #d1d5db;
}

.product-name-input {
  font-size: 18px;
  font-weight: 600;
}

.price-input-group {
  display: flex;
  align-items: center;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  background: white;
  transition: all 0.2s ease;
}

.price-input-group:focus-within {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.price-input-group.disabled {
  background-color: #f3f4f6;
  border-color: #d1d5db;
  cursor: not-allowed;
}

.price-input-group.disabled .currency {
  color: #9ca3af;
}

.currency {
  padding: 12px 0 12px 12px;
  font-weight: 600;
  color: #374151;
  font-size: 16px;
}

.price-input {
  border: none;
  padding: 12px 12px 12px 4px;
  font-size: 16px;
  font-weight: 600;
  flex: 1;
}

.price-input:focus {
  outline: none;
  border: none;
  box-shadow: none;
}

/* 分类显示样式 */
.product-category {
  display: flex;
  align-items: center;
  padding: 12px 0;
  font-size: 16px;
}

.category-label {
  color: #6b7280;
  margin-right: 8px;
  font-weight: 500;
}

.category-name {
  color: #374151;
  font-weight: 600;
  background: #f3f4f6;
  padding: 4px 12px;
  border-radius: 6px;
}

/* 分类选择样式 */
.category-select-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.category-select {
  flex: 1;
  padding: 12px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  background: white;
  transition: all 0.2s ease;
}

.category-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.category-select:disabled {
  background-color: #f3f4f6;
  color: #9ca3af;
  cursor: not-allowed;
  border-color: #d1d5db;
}

.loading-text {
  color: #6b7280;
  font-size: 14px;
  font-style: italic;
}

.edit-textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  resize: vertical;
  min-height: 100px;
  font-family: inherit;
  transition: all 0.2s ease;
}

.edit-textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 图片上传相关样式 */
.product-image-section {
  position: relative;
  z-index: 1;
}

.main-image {
  position: relative;
  overflow: hidden;
  border-radius: 8px;
}

.image-upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s ease;
  border-radius: 8px;
  z-index: 2;
  pointer-events: none;
}

.main-image:hover .image-upload-overlay {
  opacity: 1;
  pointer-events: auto;
}

.gallery-item {
  position: relative;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  z-index: 2;
  pointer-events: none;
}

.file-input {
  display: none;
}

.upload-btn {
  background: #3b82f6;
  color: white;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.2s ease;
}

.upload-btn:hover {
  background: #2563eb;
}

.url-input {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #d1d5db;
  padding: 6px 10px;
  border-radius: 4px;
  font-size: 12px;
  width: 200px;
}

.image-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.gallery-item:hover .image-actions {
  opacity: 1;
}

.remove-btn {
  background: #ef4444;
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.remove-btn:hover {
  background: #dc2626;
}

.add-image-item {
  width: 100px;
  height: 100px;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
}

.add-image-item:hover {
  border-color: #3b82f6;
  background: rgba(59, 130, 246, 0.05);
}

.add-image-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  color: #6b7280;
  font-size: 12px;
  cursor: pointer;
}

.add-image-btn .icon {
  font-size: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .product-basic-info {
    flex-direction: column;
  }

  .product-image-section {
    margin-right: 0;
    margin-bottom: 20px;
  }

  .price-input-group {
    max-width: none;
  }
}



/* URL显示样式 */
.image-url-display {
  margin-top: 10px;
  padding: 8px;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 4px;
}

.image-url-display label {
  color: white;
  font-size: 12px;
  margin-bottom: 4px;
  display: block;
}

.image-url-display .url-input {
  width: 100%;
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 3px;
  font-size: 11px;
  background: white;
  color: #333;
}

/* 禁用字段样式 */
.disabled {
  background-color: #f5f5f5 !important;
  color: #999 !important;
  cursor: not-allowed !important;
}
</style>
